package com.oocl.im.server;

import com.oocl.im.constants.ServerConstants;
import com.oocl.im.parser.IParser;
import com.oocl.im.parser.impl.Parse;
import com.oocl.im.entity.Client;
import com.oocl.im.entity.Protocol;
import com.oocl.im.handler.IHandle;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;

public class IMServerRunnable implements Runnable {


    private Socket socket;

    public IMServerRunnable() {
    }

    public IMServerRunnable(Socket socket) {
        super();
        this.socket = socket;
    }

    @Override
    public void run() {

        InputStream is = null;
        try {
            is = socket.getInputStream();

            OutputStream os = socket.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);
            ObjectInputStream ois = new ObjectInputStream(is);
            while (true) {
                Protocol protocol ;

                protocol = (Protocol) ois.readObject();
                System.out.println("got the protocol is:  "+ protocol);
                if (protocol == null) break;
                {
                    IParser parser = new Parse(oos);
                    IHandle handle = parser.parse(protocol);
                    handle.handle(new Client((String) protocol.getParams().get(ServerConstants.FROM)), protocol);
                }
            }
        }catch (SocketException e)
        {

        }
        catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {

            e.printStackTrace();

        }


    }


    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }
}






